package com.figure.core.top;

import com.figure.core.dao.message.TmcMessageMapper;
import com.figure.core.model.message.TmcMessage;
import com.figure.core.util.SpringContextUtil;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import com.taobao.api.internal.tmc.TmcClient;
import com.taobao.api.internal.toplink.LinkException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by chuanbo.wei on 2016/9/16.
 */
public class TmcMessageClient extends BaseSdk{

    private static Logger logger = LoggerFactory.getLogger(TmcMessageClient.class);

    private TmcMessageMapper tmcMessageMapper = SpringContextUtil.getApplicationContext().getBean(TmcMessageMapper.class);

    public void init(){
        TmcClient client=new TmcClient(appKey, secret,"default");//请求地址sdk默认已经封装
        client.setMessageHandler(new MessageHandler() {
            public void onMessage(Message message, MessageStatus status) {
                if(logger.isDebugEnabled()){
                    logger.debug("TMC rev message, topic is " + message.getTopic());
                }
                try {
                    TmcMessage msg = new TmcMessage();
                    msg.setTopic(message.getTopic());
                    msg.setContent(message.getContent());
                    msg.setMsgId(message.getId());
                    msg.setCreateTime(new Date());
                    msg.setOutgoingTime(message.getOutgoingTime());
                    msg.setPubAppKey(message.getPubAppKey());
                    msg.setPubTime(message.getPubTime());
                    msg.setUserId(message.getUserId());
                    msg.setUserNick(message.getUserNick());
                    tmcMessageMapper.insert(msg);
//                    if(message.getTopic())
//                    System.out.println("============");
//                    System.out.println(message.getContent());
//                    System.out.println(message.getTopic());
                    // 默认不抛出异常则认为消息处理成功
                } catch (Exception e) {
                    e.printStackTrace();
                    status.fail();// 消息处理失败回滚，服务端需要重发
                }
            }
        });
//        try {
//            client.connect();
//        } catch (LinkException e) {
//            e.printStackTrace();
//        }
//        System.out.println(client.isOnline());
//        Thread.sleep(64000000L);
    }
}
